import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as moment from 'moment';
import { In, Repository } from 'typeorm';
import { TokenEntity } from '../auth/entities/token.entity';
import { TagEntity } from '../tag/entities/tag.entity';
import { UserEntity } from '../user/entities/user.entity';
import { ArticleDto } from './dto/article.dto';
import { UpdateArticleDto } from './dto/update.article.dto';
import { ArticleEntity } from './entities/article.entity';
import { ArticleLikeEntity } from './entities/article.like.entity';
import { ArticleTagEntity } from './entities/article.tag.entity';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(ArticleEntity) // 文章
    private readonly articleRepository: Repository<ArticleEntity>,
    @InjectRepository(TagEntity) // 标签
    private readonly tagRepository: Repository<TagEntity>,
    @InjectRepository(ArticleTagEntity) // 文章标签
    private readonly articleTagRepository: Repository<ArticleTagEntity>,
    @InjectRepository(ArticleLikeEntity)
    private readonly articleLikeRepository: Repository<ArticleLikeEntity>,
  ) {}
  // 新增文章
  async createArticle(articleDto: ArticleDto, header) {
    const { token } = header;
    const article = new ArticleEntity();
    // 获取作者
    const tokenInfo = await TokenEntity.createQueryBuilder('token')
      .where('token.token = :token', {
        token: token,
      })
      .select('token.userId', 'userId')
      .addSelect(
        (s) => s.select('username').from(UserEntity, 'user').where('token.userId=user.id'),
        'username',
      )
      .getRawOne();
    Object.assign(article, articleDto);
    // 只选有用的tag
    const findTags = await this.tagRepository.find({
      where: {
        id: In(articleDto.tags),
      },
    });
    const tags = findTags.map((tag) => {
      const articleTag = new ArticleTagEntity();
      articleTag.tag = tag;
      articleTag.tagId = tag.id;
      articleTag.articleId = article.id;
      return articleTag;
    });
    const { username, userId } = tokenInfo;
    article.author = username;
    article.tags = tags;
    article.userId = userId;
    const createArticle = await this.articleRepository.create(article);
    const saveArticle = this.articleRepository.save(createArticle);
    return saveArticle;
  }
  // 获取文章
  getArticle() {
    const articleList = this.articleRepository.find();
    return articleList;
  }
  // 删除文章
  async delArticle(id: string) {
    const deleteArticle = await this.articleRepository.delete({ id });
    if (deleteArticle.affected === 1) {
      return '删除成功';
    }
    return '删除失败';
  }
  // 更新文章
  async updateArticle(updateArticleDto: UpdateArticleDto) {
    const article = await this.findById(updateArticleDto.id);
    Object.assign(article, updateArticleDto);
    if (!article) return '找不到该文章';
    const findTags = await this.tagRepository.find({
      where: {
        id: In(updateArticleDto.tags),
      },
    });
    // const articleTag = await this.articleTagRepository.findBy({ articleId: updateArticleDto.id });
    // console.log('2022-09-29 15:50:50', articleTag);
    const tags = findTags.map((tag) => {
      const articleTag = new ArticleTagEntity();
      articleTag.tag = tag;
      articleTag.tagId = tag.id;
      articleTag.articleId = article.id;
      return articleTag;
    });
    article.tags = tags;

    // const updateArticle = await this.articleRepository
    //   .createQueryBuilder()
    //   .update('article')
    //   .set({ ...article })
    //   .where('id = :id', { id: updateArticleDto.id })
    //   .execute();
    // if (updateArticle.affected === 1) {
    //   return '更新成功';
    // }
    // 删除以前文章对应的tag
    const delTag = await this.articleTagRepository.delete({ articleId: updateArticleDto.id });
    const saveArticle = await this.articleRepository.save(article);
    console.log('2022-09-29 16:31:36', delTag);
    return saveArticle;
  }
  /**
   * @Author: laotongshu
   * @Date: 2022-10-09 10:32:04
   * @LastEditors: laotongshu
   * @Description: 根据id查询文章详情
   * @param {Object} {}
   * @return {*}
   */
  articleById(id: string, ipAddress: string) {
    console.log('2022-10-09 13:54:20', ipAddress);
    const articleDetail = this.articleRepository.findBy({
      id,
    });
    return articleDetail;
  }
  // 根据id查找单个文章
  async findById(id: string) {
    return this.articleRepository.findOne({
      where: { id },
    });
  }
  /**
   * @Author: laotongshu
   * @Date: 2022-10-09 10:33:17
   * @LastEditors: laotongshu
   * @Description: 根据文章点赞
   * @param aid: 文章id
   * @param uid: 用户id
   * @return {*}
   */
  async clickLike(aid: string, uid: string) {
    // 判断是否已经点赞过
    const hasLike = await this.hashLikeByUid(aid, uid);
    let result;
    if (hasLike) {
      // 取消点赞
      result = await this.unlikeById(aid, uid);
    } else {
      result = await this.likeById(aid, uid);
    }
    return result;
  }
  /**
   * @Author: laotongshu
   * @Date: 2022-10-09 10:35:05
   * @LastEditors: laotongshu
   * @Description: 判断是否已经点赞过
   * @param aid: 文章id
   * @param uid: 用户id
   * @return : boolean
   */
  async hashLikeByUid(aid, uid) {
    const like = await this.articleLikeRepository.findOne({
      where: {
        articleId: aid,
        userId: uid,
      },
    });
    console.log('2022-10-09 10:41:18', like);
    return !!like;
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-09 10:42:12
   * @LastEditors: laotongshu
   * @Description: 根据文章id点赞
   * @param {Object} {}
   * @return {*}
   */
  likeById(aid, uid) {
    const like = new ArticleLikeEntity();
    like.articleId = aid;
    like.userId = uid;
    return this.articleLikeRepository.save(like);
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-09 10:41:48
   * @LastEditors: laotongshu
   * @Description: 根据文章id取消点赞
   * @param {Object} {}
   * @return {*}
   */
  unlikeById(aid, uid) {
    return this.articleLikeRepository.delete({
      userId: uid,
      articleId: aid,
    });
  }
}
